package name.sakanacatcher.controller;

import name.sakanacatcher.entity.Group;
import name.sakanacatcher.entity.Message;
import name.sakanacatcher.entity.UnRead;
import name.sakanacatcher.entity.User;
import name.sakanacatcher.service.AuthService;
import name.sakanacatcher.service.InformService;
import name.sakanacatcher.service.UserService;
import name.sakanacatcher.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/inform")
public class InformController {

    @Autowired
    InformService informService;

    @Autowired
    UserService userService;

    @Autowired
    ResultUtil resultUtil;

    @Autowired
    AuthService authService;

    @GetMapping("/p2p/list")
    public Map<String, Object> getP2PList(){
        User reqUser = userService.getUserRepository().getByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
        List<UnRead> unReadList = informService.getAllP2PUnReadByUid(reqUser.getId());
        return resultUtil.successResult("Get Success", Map.of("items", unReadList));
    }


//    @GetMapping("/p2p/check")
//    public Map<String, Object> checkP2PGroup(@RequestParam String name){
//        String[] userIds = name.split("_");
//        String groupName = name;
//        if(Integer.parseInt(userIds[0])  >= Integer.parseInt(userIds[1]) ){
//            groupName = new String(userIds[1] + "_" + userIds[0]);
//        }
//        if(informService.getGroupRepository().existsByName(groupName)) {
//            return resultUtil.successResult("Get Success", true);
//        }
//        else {
//            Group group = new Group(groupName,"p2p")
//        }
//
//    }

//    @GetMapping("/all/list")
//    public Map<String, Object> getAlwaysGroup(){
//        User reqUser = userService.getUserRepository().getByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
//        List<Group> groups = informService.getAllGroupByUid(reqUser.getId());
//        return resultUtil.successResult("Get Success", Map.of("items",groups));
//    }

    @GetMapping("/group/history")
    public Map<String, Object> getGroupHistory(@RequestParam(name = "page", required = true) int page,
                                        @RequestParam(name = "limit", required = true) int limit,
                                        @RequestParam(name = "groupName", required = true) String groupName){
        User reqUser = userService.getUserRepository().getByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
        Group group = informService.getP2PGroupByName(groupName);
        informService.cleanUnRead(reqUser.getId(),group.getId());
        List<Message> messages = informService.getAllMessageByGroupName(groupName);
        int total = messages.size();
        int totalPage = (int)Math.ceil(total / (double)limit);
        if(page <= totalPage && page >= 1){
            if(page * limit > total){
                messages = messages.subList((page - 1)*limit, total);
            }
            else {
                messages = messages.subList((page - 1)*limit,page * limit);
            }
        }
        else{
            messages = messages.subList(0,0);
        }
        return resultUtil.successResult("Get Success", Map.of("items", messages ));
    }

    @GetMapping("/unRead/list")
    public Map<String, Object> getUnReadList(@RequestParam(name = "page", required = true) int page,
                                               @RequestParam(name = "limit", required = true) int limit) {
        User reqUser = userService.getUserRepository().getByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
        List<UnRead> unReadList = informService.getUnReadRepository().getAllByUserId(reqUser.getId());
        System.out.println(unReadList);
        unReadList = unReadList.stream().filter(
                unRead -> {
                    return unRead.getUser().getId() == reqUser.getId();
                }
        ).collect(Collectors.toList());

        System.out.println(unReadList);
        int total = unReadList.size();
        int totalPage = (int)Math.ceil(total / (double)limit);
        if(page <= totalPage && page >= 1){
            if(page * limit > total){
                unReadList = unReadList.subList((page - 1)*limit, total);
            }
            else {
                unReadList = unReadList.subList((page - 1)*limit,page * limit);
            }
        }
        else{
            unReadList = unReadList.subList(0,0);
        }
        return resultUtil.successResult("Get Success", Map.of("items", unReadList ));
    }

        @GetMapping("/group/info")
    public Map<String,Object> sendP2PMessage(@RequestParam(name = "name") String groupName) {
        return resultUtil.successResult("send Success",Map.of("items",informService.getP2PGroupByName(groupName)));
    }

    @PostMapping("/group/send")
    public Map<String,Object> sendP2PMessage(@RequestBody Map<String, Object> data){
        Message message = informService.getMessageRepository().findById(informService.sendMessage(data));
        return resultUtil.successResult("send Success",Map.of("items",message));
    }



}
